package domain.worm;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.appearances.Sprite;
import com.uqbar.vainilla.events.constants.Key;

public class StandbyState extends WormState {
	
	public StandbyState(Worm worm) {
		super(worm);
	}

	@Override
	public void update(DeltaState deltaState) {
		
		if (deltaState.isKeyBeingHold(Key.RIGHT) | deltaState.isKeyPressed(Key.RIGHT)){
			this.getWorm().setAppearance(this.getWorm().getWalkingRightAnimation());
			this.walk(deltaState, 1);
		}

		if (deltaState.isKeyBeingHold(Key.LEFT) | deltaState.isKeyPressed(Key.LEFT)){
			this.getWorm().setAppearance(this.getWorm().getWalkingLeftAnimation());
			this.walk(deltaState, -1);
		}
		
		if (!deltaState.isKeyBeingHold(Key.LEFT) & !deltaState.isKeyBeingHold(Key.RIGHT)){
			this.getWorm().setStill(Sprite.fromImage("/wstill"+this.getWorm().getDir()+".PNG"));
			this.getWorm().setAppearance(this.getWorm().getStill());
		}

		if (deltaState.isKeyBeingHold(Key.ENTER) | deltaState.isKeyPressed(Key.ENTER)){
			this.getWorm().setState(new JumpingState(this.getWorm()));
		}
		if (deltaState.isKeyBeingHold(Key.UP) | deltaState.isKeyPressed(Key.UP)){
			this.getWorm().setState(new PointingState(this.getWorm()));
		}
		if (deltaState.isKeyBeingHold(Key.DOWN) | deltaState.isKeyPressed(Key.DOWN)){
			this.getWorm().setState(new PointingState(this.getWorm()));
		}
		
	}

	private void walk(DeltaState deltaState, int dir) {
		this.getWorm().setDir(dir);
		if(this.getWorm().canWalk(deltaState, dir)){
			this.normalWalk(deltaState, dir);
		}
		else {
			if (this.canJump(deltaState, dir)){
				this.jumpingWalk(deltaState, dir);
			}else{
				this.getWorm().setStill(Sprite.fromImage("/wstill"+dir+".PNG"));
				this.getWorm().setAppearance(this.getWorm().getStill());}
			
		}
	}

	private boolean canJump(DeltaState delta, int dir) {
		double nX, nY;
		nX = this.getWorm().getX() + this.getWorm().getSpeed()*dir*delta.getDelta() +dir;
		nY = this.getWorm().getY() + this.getWorm().getMoveCap();
		return this.getWorm().getSceneTableComps().nonCollisionOn(nX, nY, this.getWorm());
		
	}

	private void jumpingWalk(DeltaState deltaState, int dir) {
		//this.getWorm().setX(this.getWorm().getX() - dir*2);
		//this.getWorm().nonSolidMove(deltaState, 500, 0, this.getWorm().getMoveCap(), -dir, 0);
		this.getWorm().updateCoords(0, this.getWorm().getMoveCap());
		this.getWorm().nonSolidMove(deltaState, this.getWorm().getSpeed(), dir*5, 0, 0, 0);
		this.getWorm().setState(new StateFalling(this.getWorm()));
	}

	private void normalWalk(DeltaState delta, int dir) {
		double diffX, diffY;
		diffX = delta.getDelta()*this.getWorm().getSpeed()*dir;
		
		this.getWorm().updateCoords(diffX, 0);
		this.getWorm().setState(new StateFalling(this.getWorm()));
		
	}



}
